<template>
  <div class="app-container">
    <div class="search-container">
      <div class=" mb10" style="color: #00c0ef;font-size: 13px">
        特殊说明：天数选择1，摆第二天药品，摆药时间从明天0点开始截止后天0点。天数选择2，摆明天以及后天药品，摆药时间截止大后天0点。在此时间段内已经摆过的药品不能再次摆药。
        医生下医嘱时勾选 【首日是否摆药】为是 ，默认摆当天药品
        <br/>
        摆药时间段：<span style="color: #ff0202">{{ $parseTime($addDay(1, new Date()), '{y}-{m}-{d} 00:00:00') }}
                截止 {{ $parseTime($addDay(lastDispensingDays, new Date()), '{y}-{m}-{d} 00:00:00') }}</span>
      </div>
      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" :rules="rules" label-width="100px">
        <el-form-item prop="dispensingDays">
                    <span slot="label">
                        <span class="mr10" style="color: #f50f0f"><strong>摆药天数</strong></span>
                   </span>
          <el-input
            v-model="queryParams.dispensingDays"
            clearable
            placeholder="请输入摆药天数"
            style="width: 120px"
            @blur="handleQuery"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="病区" prop="wardAdmissionToName">
          <dept-vs-bed-list v-model="queryParams.wardAdmissionToName" :clinical-sign-str="'3'"
                            :dept-id="queryParams.wardAdmissionTo"
                            :org-id="userInfo.orgId" :placeholder="'请选择入院病区'"
                            style="width: 120px" @deptChange="wardChange"/>
        </el-form-item>
        <el-form-item label="住院号" prop="hospitalNo">
          <el-input
            v-model="queryParams.hospitalNo"
            clearable
            placeholder="请输入住院号"
            style="width: 120px"
            @keyup.enter="getPatientList"
          />
        </el-form-item>
        <el-form-item label="床位号" prop="bedNo">
          <el-input
            v-model="queryParams.bedNo"
            clearable
            placeholder="请输入床位号"
            style="width: 120px"
            @keyup.enter="getPatientList"
          />
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入患者姓名"
            style="width: 120px"
            @keyup.enter="getPatientList"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="getPatientList" @resetQuery="resetQuery"/>
          <el-col :span="1.5" class="ml10">
            <el-button
              plain
              type="primary"
            >
              <template
                #icon>
                <i-ep-plus/>
              </template>
              查询库存量不足的药品
            </el-button>
          </el-col>
          <el-col :span="1.5" class="ml10">
            <el-button
              plain
              type="success"
            >
              <template #icon>
                <i-ep-edit/>
              </template>
              一键更换批次
            </el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="5">
      <el-col :span="6">
        <el-table v-adaptive="20" :border="true" :data="patientList"
                  :header-cell-style="$headerCellStyle"
                  :stripe="true" highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column align="center" label="住院号" prop="hospitalNo" width="160"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="姓名" prop="name"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="病区"
                           prop="wardCodeName"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="床位号" prop="bedNo"/>
        </el-table>
      </el-col>
      <el-col :span="18">
        <el-tabs v-if="ids.length>0" type="border-card" @tab-click="handleClick">
          <el-tab-pane label="药品汇总" name="0">
            <el-form ref="drugDispQueryParamsRef" :inline="true" :model="queryParams" :rules="rules"
                     label-width="100px">
              <el-form-item label="用药单方式" prop="medicalWay">
                <el-select v-model="queryParams.medicalWay" class="width-120"
                           clearable placeholder="请选择" @change="medicalWayChange">
                  <el-option key="999" label="全部" value="999"/>
                  <el-option v-for="dict in dictDataMap['medical_way']" :key="dict.dictValue"
                             :label="dict.dictLabel"
                             :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <el-form-item label="长/临" prop="repeatIncaditor">
                <el-radio-group v-model="queryParams.repeatIncaditor"
                                @change="repeatIncaditorHandleQuery">
                  <el-radio-button label="全部" value=""/>
                  <template v-for="(tag, index) in dictDataMap['order_type']">
                    <el-radio-button :label="tag.dictLabel" :value="tag.dictValue"/>
                  </template>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <query-form-button @handleQuery="drugDispHandleQuery" @resetQuery="drugDispResetQuery"/>
                <el-button type="primary" @click="submitForm">摆药确认</el-button>
                <el-button v-if="drugDispCollectList.length >0" type="danger" @click="fillOutTraceabilityCode">
                  填写追溯码
                </el-button>
              </el-form-item>
            </el-form>
            <el-table v-adaptive="35" :border="true" :data="drugDispCollectList"
                      :header-cell-style="$headerCellStyle" :stripe="true" :summary-method="getSummaries"
                      highlight-current-row
                      show-summary>
              <el-table-column :show-overflow-tooltip="true" align="center" label="长/临"
                               prop="repeatIncaditor" width="70">
                <template #default="scope">
                  <dict-data-tag :options="dictDataMap['order_type']"
                                 :value="scope.row.repeatIncaditor"/>
                  <!--                                    <span v-if="!queryParams.repeatIncaditor">全部</span>-->
                  <!--                                    <span v-else><dict-data-tag-->
                  <!--                                        :options="dictDataMap['order_type']"-->
                  <!--                                        :value="scope.row.repeatIncaditor"/></span>-->
                </template>
              </el-table-column>
              <el-table-column align="center" label="天数" prop="dispensingDays" width="60">
                <template #default="scope">
                  <span class="ys-css">{{ queryParams.dispensingDays }}</span>
                </template>
              </el-table-column>
              <el-table-column :show-overflow-tooltip="true" align="center" label="药品名称"
                               prop="orderText" />
              <el-table-column :show-overflow-tooltip="true" align="center" label="编码" prop="drugCode"
                               width="120"/>
              <el-table-column :show-overflow-tooltip="true" align="center" label="规格"
                               prop="drugSpec" width="150"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="数量"
                               width="110px">
                <template #default="scope">
                  <template v-if="scope.row.usedQuantityMin > 0">
                    <!--小包装-->
                    <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.usedQuantityMin }}
                    </div>
                  </template>
                  <!--大包装-->
                  <template v-if="scope.row.usedQuantityMax > 0">
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.drugUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.usedQuantityMax }}
                    </div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="单价(大包装)" prop="retailPrice" width="140">
                <template #default="scope">
                                    <span class="ret-ys-css">{{
                                        parseFloat(scope.row.retailPrice).toFixed(2)
                                      }}</span>元
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="单价(小包装)" prop="retailPrice" width="130">
                <template #default="scope">
                                    <span class="ys-css">{{
                                        parseFloat(scope.row.retailPriceMin).toFixed(2)
                                      }}</span>元
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="金额" prop="itemRetailPriceShow" width="130">
                <template #default="scope">
                  <span class="ys-css">{{ scope.row.itemRetailPriceShow }}</span>元
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="库存量"
                               prop="minUnits" width="177px">
                <template #default="scope">
                  <template v-if="scope.row.quantityMin > 0">
                    <!--小包装-->
                    <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                                   style="float: right"/>
                    <div class="ys-css" style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.quantityMin }}
                    </div>
                  </template>
                  <!--大包装-->
                  <template v-if="scope.row.quantityMax > 0">
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.drugUnits"
                                   style="float: right"/>
                    <div class="ys-css" style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.quantityMax }}
                    </div>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="摆药明细" name="1">
            <el-table :border="true" :data="patientDispInfoDetailList" :header-cell-style="$headerCellStyle"
                      :stripe="true" height="860" highlight-current-row>
              <el-table-column align="center" label="住院号" prop="hospitalNo" width="100"/>
              <el-table-column :show-overflow-tooltip="true" align="center" label="姓名" prop="name"
                               width="90"/>
              <el-table-column :show-overflow-tooltip="true" align="center" label="病区" prop="wardCodeName"
                               width="100"/>
              <el-table-column :show-overflow-tooltip="true" align="center" label="床位号" prop="bedNo"
                               width="60"/>
              <el-table-column :show-overflow-tooltip="true" align="center" label="截止摆药时间" prop="lastDispTime"
                               width="160">
                <template #default="scope">
                  {{ $parseTime(scope.row.lastDispTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="数量"
                               width="140px">
                <template #default="scope">
                  <template v-if="scope.row.usedQuantityMin > 0">
                    <!--小包装-->
                    <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.usedQuantityMin }}
                    </div>
                  </template>
                  <!--大包装-->
                  <template v-if="scope.row.usedQuantityMax > 0">
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.packageUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.usedQuantityMax }}
                    </div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column :show-overflow-tooltip="true" align="center" label="长/临"
                               prop="repeatIncaditor" width="80">
                <template #default="scope">
                  <dict-data-tag :options="dictDataMap['order_type']"
                                 :value="scope.row.repeatIncaditor"/>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="库存量"
                               prop="minUnits" width="150px">
                <template #default="scope">
                  <template v-if="scope.row.quantityMin > 0">
                    <!--小包装-->
                    <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                                   style="float: right"/>
                    <div class="ys-css" style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.quantityMin }}
                    </div>
                  </template>
                  <!--大包装-->
                  <template v-if="scope.row.quantityMax > 0">
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.packageUnits"
                                   style="float: right"/>
                    <div class="ys-css" style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.quantityMax }}
                    </div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="医嘱内容"
                               prop="itemName" width="160px">
                <template #default="scope">
                  <span class="ys-css">{{ scope.row.itemName }}</span>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号"
                               prop="batchNo" width="100px">
                <template #default="scope">
                  {{ scope.row.drugStockVo.batchNo }}
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品规格"
                               prop="spec" width="110px">
                <template #default="scope">
                  {{ scope.row.packSize === '1' ? scope.row.minSpec : scope.row.packageSpec }}
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="开单科室"
                               prop="applyDeptName" width="110px"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="开单医生"
                               prop="applyUserName" width="110px"/>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-empty v-else description="暂无数据，请勾选左侧患者列表后，再操作。"/>
      </el-col>
    </el-row>
    <traceability-code ref="traceabilityCodeRef" :org-id="queryParams.orgId" @submit-form-ok="submitFormOk"/>
  </div>
</template>

<script lang="ts">
export default {
  name: "DrugDispIndex"
}
</script>

<script lang="ts" setup>
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user.ts";
import {listBedRecAndPatientDoctor} from "@/api/hospitalization/patVisit.ts";
import {getPatientDispInfo, getPatientDispInfoDetail, drugDispQuantityDeduction} from "@/api/orders/orders.ts";
import {selectConfigByCache} from "@/api/system/orgConfig.ts";
import {addDrugForTrack} from "@/api/drug/drugForTrack.ts";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any
const currentSelectDept = proxy.$currentSelectDept
/**
 * 医保-药品销售、入库追溯码是否必填 Y 必填 N不必填
 */
const medicalInsuranceTraceabilityCode = ref("N")
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'medical_way', 'order_type'))
const patientList = ref([])
const drugDispCollectList = ref([])
const patientDispInfoDetailList = ref([])
const drugDispList = ref([])
const ids = ref([]);
const single = ref(true);
const queryParams = ref<any>({
  dispensingDays: 1 as number,
  medicalWay: '999',
  repeatIncaditor: '',
  orgId: userInfo.orgId
})
const queryParamsRef = ref()
const traceabilityCodeRef = ref()
const lastDispensingDays = ref<number>(2)
const drugDispQueryParamsRef = ref()

// 表单校验
const rules = ref({
  dispensingDays: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  wardAdmissionToName: [
    {required: true, message: '请选择病区', trigger: "change"}
  ]
})

function handleQuery() {
  lastDispensingDays.value = Number(queryParams.value.dispensingDays) + 1 as number
  (queryParamsRef.value as any).validate(valid => {
    if (valid) {
      // getPatientList()
      getPatientDispInfoFun()
    }
  })

}

function resetQuery() {
  queryParamsRef.value.resetFields()
  queryParams.value.wardAdmissionTo = ""
  queryParams.value.wardAdmissionToName = ""
  patientList.value = []
}

function wardChange(obj) {
  queryParams.value.wardAdmissionToName = obj.wardCodeName
  queryParams.value.wardAdmissionTo = obj.wardCode
  getPatientList()
}

/**
 * 用药单方式选择事件
 */
function medicalWayChange() {

}

/**
 * 长期临时选择事件
 */
function repeatIncaditorHandleQuery() {
  getPatientDispInfoFun()
}

/**
 * 药品合计搜索事件
 */
function drugDispHandleQuery() {
  getPatientDispInfoFun()
}

/**
 * 药品合计重置事件
 */
function drugDispResetQuery() {
  drugDispQueryParamsRef.value.resetFields()
}


// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.visitId);
  single.value = selection.length != 1;
  getPatientDispInfoFun()

}

/**
 * 查询摆药汇总列表
 */
function getPatientDispInfoFun() {
  drugDispCollectList.value = []
  if (ids.value.length > 0) {
    const param = {
      dispensingDays: queryParams.value.dispensingDays,
      repeatIncaditor: queryParams.value.repeatIncaditor,
      medicalWay: queryParams.value.medicalWay,
      visitIds: ids.value,
      wardCode: queryParams.value.wardAdmissionTo,
      orgId: queryParams.value.orgId
    }
    getPatientDispInfo(param).then((res: resType) => {
      let data = res.data
      if (data) {
        data.forEach(item => {
          let itemRetailPriceShow = Number(item.computeAmount * item.retailPriceMin)
          item.itemRetailPriceShow = itemRetailPriceShow.toFixed(2)
          item.quantityMax = Math.floor(item.quantity / item.packageNum)
          item.quantityMin = item.quantity % item.packageNum
          item.usedQuantityMax = Math.floor(item.computeAmount / item.packageNum)
          item.usedQuantityMin = item.computeAmount % item.packageNum
        })
        drugDispCollectList.value = data
      }
    })
  }
}

/**
 * 查询摆药明细列表
 */
function getPatientDispInfoDetailFun() {
  patientDispInfoDetailList.value = []
  if (ids.value.length > 0) {
    const param = {
      dispensingDays: queryParams.value.dispensingDays,
      repeatIncaditor: queryParams.value.repeatIncaditor,
      medicalWay: queryParams.value.medicalWay,
      visitIds: ids.value,
      wardCode: queryParams.value.wardAdmissionTo,
      orgId: queryParams.value.orgId,
      // 是否查询明细 Y 是
      isQueryDetail: "Y"
    }
    getPatientDispInfoDetail(param).then((res: resType) => {
      let data = res.data
      if (data) {
        data.forEach(item => {
          let itemRetailPriceShow = Number(item.amount * item.retailPriceMin)
          item.itemRetailPriceShow = itemRetailPriceShow.toFixed(2)
          item.quantityMax = Math.floor(item.currentStock / item.packageNum)
          item.quantityMin = item.currentStock % item.packageNum
          item.usedQuantityMax = Math.floor(item.amount / item.packageNum)
          item.usedQuantityMin = item.amount % item.packageNum
        })        
        patientDispInfoDetailList.value = data
      }
    })
  }
}

/**
 * 获取病区患者信息
 */
function getPatientList() {
  if (queryParams.value.wardAdmissionTo) {
    const param = {
      wardCode: queryParams.value.wardAdmissionTo,
      orgId: userInfo.orgId,
      hospitalNo: queryParams.value.hospitalNo,
      name: queryParams.value.name,
      bedNo: queryParams.value.bedNo
    }
    listBedRecAndPatientDoctor(param).then((res: resType) => {
      if (res.data) {
        patientList.value = res.data
      }
    })
  } else {
    ElMessage.error("请先选择医生的权限科室后，再操作。")
  }
}


const getSummaries = (param: any) => {
  const {columns, data} = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 7) {
      sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
        '合计金额：',
      ])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (column.property === 'itemRetailPriceShow') {
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `￥ ${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return (Number(prev) + Number(curr)).toFixed(2)
          } else {
            return (Number(prev)).toFixed(2)
          }
        }, 0)} 元`
      } else {
        sums[index] = 'N/A'
      }
    }

  })
  return sums
}

/**
 * 摆药确认
 */
function submitForm() {
  if (medicalInsuranceTraceabilityCode.value === "N") {
    // 不启用追溯码直接发药保存
    submitFormThisConfirm()
  } else {
    // 启用追溯码，首先保存追溯码后再发药保存
    fillOutTraceabilityCode();
  }
}

/**
 * 此页面最终摆药确认事件
 */
function submitFormThisConfirm() {
  if (ids.value.length > 0) {

    ElMessageBox.confirm('确认要进行摆药确认吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      submitFormThisOk()
    }).catch(() => {
    })
  } else {
    ElMessage.error("请勾选左侧 患者后，再操作。")
  }
}

function submitFormThisOk () {
  const param = {
    dispensingDays: queryParams.value.dispensingDays,
    repeatIncaditor: queryParams.value.repeatIncaditor,
    medicalWay: queryParams.value.medicalWay,
    visitIds: ids.value,
    wardCode: queryParams.value.wardAdmissionTo,
    orgId: queryParams.value.orgId,
    // 是否查询明细 N 否
    isQueryDetail: "N"
  }
  drugDispQuantityDeduction(param).then(() => {
    getPatientDispInfoFun()
    ElMessage.success("摆药成功")
  })
}

/**
 * 从药品追溯码点击保存后的提交事件
 * @param form
 */
function submitFormOk(form: any) {
  console.log("form", form)
  let drugForTrackList: any = []
  form.traceabilityCodeList.forEach((item: any) => {
    const drugForTrack: any = {
      mdtrtId: item.visitId,
      sourceType: "2",
      applyId: item.applyId,
      drugDispSelectTempId: item.remarks,
      itemCode: item.drugCode,
      itemName: item.drugName,
      packageSpec: item.packageSpec,
      priceId: item.priceId,
      infoId: item.drugInfoId,
      trackCode: item.trackCode,
      orgId: item.orgId,
      delFlag: "0"
    }
    drugForTrackList.push(drugForTrack)
  })
  addDrugForTrack({"drugForTrackList": drugForTrackList}).then(() => {
    traceabilityCodeRef.value.dialogClose()
    submitFormThisOk();
    ElMessage.success("保存成功")
  })
}


function handleClick(tab, _event) {
  if (tab.props.name === '0') {
    getPatientDispInfoFun()
  } else {
    getPatientDispInfoDetailFun()
  }
}

/**
 * 填写追溯码
 */
function fillOutTraceabilityCode() {
  debugger
  const drugDispSelectTempIds = drugDispCollectList.value.map((item: any) => item.drugDispSelectTempId);
  nextTick(() => {
    const obj = {
      ids: drugDispSelectTempIds,
      // 发药 1 ； 医嘱摆药 2
      type: "2"
    }
    traceabilityCodeRef.value.initOpenTraceabilityCode(obj)
  })
}

/**
 * 通过orgId key获取对应的机构参
 */
function selectConfigByCacheFun() {
  // 是否启用电子发票流程
  selectConfigByCache(userInfo.orgId, "medical.insurance.traceabilityCode").then((res => {
    medicalInsuranceTraceabilityCode.value = res.data.configValue
  }))
}

onMounted(() => {
  selectConfigByCacheFun()
})


</script>
